package com.ywt.cda.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

public class BaiduMapApi
{
	private static final Logger logger = Logger.getLogger(BaiduMapApi.class);

	private static final String key = "f247cdb592eb43ebac6ccd27f796e2d2";

	private static final String url = "http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s";

	private static BaiduMapApi instance = new BaiduMapApi();

	private HttpClient httpClient = HttpClients.createDefault();

	private BaiduMapApi()
	{
		logger.debug("BaiduMapApi init...");
	}

	public static BaiduMapApi getInstance()
	{
		return instance;
	}

	public String[] getChinaCoordinate(String address)
	{
		String newUrl = String.format(url, address, key);
		HttpGet getRequest = new HttpGet(newUrl);
		getRequest.addHeader("accept", "application/json");
		CloseableHttpResponse response = null;
		BufferedReader br = null;
		InputStreamReader isr = null;
		try
		{
			try
			{
				response =  (CloseableHttpResponse) httpClient.execute(getRequest);
			}
			catch (ClientProtocolException e)
			{
				logger.error("post failed:" + e.toString());
				httpClient = HttpClients.createDefault();
				return null;
			}
			catch (IOException e)
			{
				logger.error("post failed:" + e.toString());
				httpClient = HttpClients.createDefault();
				return null;
			}

			if (response.getStatusLine().getStatusCode() != 200)
			{
				logger.error("post failed:getStatusLine->getStatusCode:"
						+ response.getStatusLine().getStatusCode());
				return null;
			}
			
			isr = new InputStreamReader((response.getEntity().getContent()));
			br = new BufferedReader(isr);
			String output = null;
			StringBuffer sb = new StringBuffer();
			//sSystem.out.println("Output from Server .... \n");
			while ((output = br.readLine()) != null)
			{
				//System.out.println(output);
				if (StringUtils.isNotBlank(output))
				{
					sb.append(output);
				}
			}
			String str = sb.toString();
			if (StringUtils.isNotBlank(str))
			{
				JSONObject result = JSONObject.parseObject(str);
				if ("OK".equals(result.getString("status")))
				{
					if (result.containsKey("result"))
					{
						if (result.getJSONObject("result").containsKey("location")
								&& result.getJSONObject("result").get("location") instanceof JSONObject)
						{
							JSONObject location = result.getJSONObject("result").getJSONObject("location");
							if (location.containsKey("lng")
									&& location.containsKey("lat"))
							{
								return new String[]
								{
										location.getString("lng"),
										location.getString("lat")
								};
							}
						}
					}
				}
			}
		}
		catch (Exception e)
		{
			logger.error("query map Coordinate failed:" + e.toString());
			return null;
		}
		//关闭IO流
		finally
		{
			try
			{
				if (null != isr)
				{
					isr.close();
				}
			}
			catch (IOException e)
			{
				logger.error("close InputStreamReader failed:" + e.toString());
			}
			try
			{
				if (null != br)
				{
					br.close();
				}
			}
			catch (IOException e)
			{
				logger.error("close BufferedReader failed:" + e.toString());
			}
			try
			{
				if (null != response)
				{
					response.close();
				}
			}
			catch (IOException e)
			{
				logger.error("close CloseableHttpResponse failed:" + e.toString());
			}
		}
		return null;
	}
}
